<template>
  <div>
    <input type="text" v-model="searchInfo" placeholder="搜索地址" />
    <button :disabled="searchInfo.trim().length == 0" @click="search">搜索</button>
    <button :disabled="searchInfo.trim().length == 0" @click="searchNearby">搜索周边</button>
  </div>
  <div class="map-container" id="amap-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
const mapError = ref({})

const searchInfo = ref('')
const markerList = ref([])
const search = () => {
  // 清理所有标记
  markerList.value.forEach((item) => {
    map.value.remove(item)
  })
  //@ts-expect-error @typescript-eslint/no-explicit-any
  ps.value.search(searchInfo.value, (status, result) => {
    if (status === 'complete') {
      console.log('搜索成功：', result)
      //@ts-expect-error @typescript-eslint/no-explicit-any
      markerList.value = result.poiList.pois.map((item) => {
        //@ts-expect-error @typescript-eslint/no-explicit-any
        return new AMap.Marker({
          position: item.location,
          title: item.name,
        })
      })
      // 添加到地图
      markerList.value.forEach((item) => {
        map.value.add(item)
      })
    } else {
      console.log('搜索错误：', status)
    }
  })
}

const searchNearby = () => {
  // 清理所有标记
  markerList.value.forEach((item) => {
    map.value.remove(item)
  })
  //@ts-expect-error @typescript-eslint/no-explicit-any
  ps.value.searchNearBy(searchInfo.value, lnglat.value, 1000, (status, result) => {
    if (status === 'complete') {
      console.log('搜索周边成功：', result)
      //@ts-expect-error @typescript-eslint/no-explicit-any
      markerList.value = result.poiList.pois.map((item) => {
        //@ts-expect-error @typescript-eslint/no-explicit-any
        return new AMap.Marker({
          position: item.location,
          title: item.name,
        })
      })
      // 添加到地图
      markerList.value.forEach((item) => {
        map.value.add(item)
      })
    } else {
      console.log('搜索周边错误：', status)
    }
  })
}

const lnglat = ref()
const map = ref()
const city = ref('430702')
const ps = ref()

const getLocation = () => {
  //@ts-expect-error @typescript-eslint/no-explicit-any
  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true, // 是否使用高精度定位，默认：true
    timeout: 10000, // 设置定位超时时间，默认：无穷大
    offset: [10, 20], // 定位按钮的停靠位置的偏移量
    zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    position: 'RB', //  定位按钮的排放位置,  RB表示右下
  })
  map.value.addControl(geolocation)
  //@ts-expect-error @typescript-eslint/no-explicit-any
  geolocation.getCurrentPosition((s, r) => {
    if (s == 'complete') {
      console.log('定位成功：', r)
      lnglat.value = r.position
      map.value.setCenter(r.position)
      mapError.value = {}
      // 获取城市信息
      getCity()
    } else {
      console.log('定位错误：', s)
      mapError.value = r
    }
  })
}
const getCity = () => {
  // 逆地理编码
  //@ts-expect-error @typescript-eslint/no-explicit-any
  const geocoder = new AMap.Geocoder({
    city: '430702',
  })
  //@ts-expect-error @typescript-eslint/no-explicit-any
  geocoder.getAddress(lnglat.value, (status, result) => {
    if (status === 'complete') {
      console.log('逆地理编码成功：', result)
      city.value = result.regeocode.addressComponent.adcode
      //@ts-expect-error @typescript-eslint/no-explicit-any
      ps.value = new AMap.PlaceSearch({
        city: city.value,
        map: map.value,
      })
    } else {
      console.log('逆地理编码错误：', status)
    }
  })
}

const loadMap = () => {
  AMapLoader.load({
    key: 'e01499dbab923bc5913783dde252868b', //申请好的 Web 端开发 Key，首次调用 load 时必填
    version: '2.0', //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.ToolBar',
      'AMap.Scale',
      'AMap.Geolocation',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.Geocoder',
    ], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['AMap.Scale','...','...']
    Loca: {
      //是否加载 Loca， 缺省不加载
      version: '2.0', //Loca 版本
    },
  })
    .then((AMap) => {
      map.value = new AMap.Map('amap-container', {
        animateEnable: false,
      }) //"container"为 <div> 容器的 id
      map.value.addControl(new AMap.ToolBar({ position: 'LT' }))
      map.value.addControl(new AMap.Scale()) //添加比例尺组件到地图实例上
      // 获取当前位置
      getLocation()
    })
    .catch((e) => {
      console.error(e) //加载错误提示
    })
}

onMounted(() => {
  loadMap()
})

onUnmounted(() => {
  map.value?.destroy()
})
</script>

<style scoped>
.map-container {
  height: 90vh;
  width: 90vw;
  margin: 5px auto;
}

.ac {
  position: fixed;
  top: 6rem;
  right: 8rem;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px;
  border-radius: 5px;
  z-index: 100;
  display: flex;
  flex-direction: column;
  width: 20rem;
  input {
    width: 15rem;
  }
  color: #fff;
  .tip {
    cursor: pointer;
    margin: 5px;
    &:hover {
      color: #00f;
    }
  }
}
</style>
